//
//  ClubInfoViewController.m
//  SportSocial
//
//  Created by yull on 15/1/10.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "PlaceInfoViewController.h"
#import "PlaceInfoTopCell.h"
#import "PlaceInfoAddressPhoneCell.h"
#import "PlaceInfoBottomCell.h"
#import "PlaceMapViewController.h"
#import "BMapKit.h"
#import "UIScrollView+PullToRefresh.h"
#import "NDRefreshLoadMoreContainView.h"
#import "PlaceNet.h"
#import "PlaceActivity.h"
#import "GroupInfoActivityCell.h"
#import "PlacePhotoViewController.h"

@interface PlaceInfoViewController () <UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,PlaceInfoTopCellDelegate>

@property (nonatomic, strong) UITableView *infoTableView;

@property (nonatomic, strong) Place *place;

@property (nonatomic, strong) NSMutableArray *activityArray;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger totalPage;

@property (nonatomic, strong) NSMutableArray *firstPhotoArray;
@property (nonatomic, assign) NSInteger totalPhotoPage;
@property (nonatomic, assign) NSInteger totalPhotoNumber;

@end

@implementation PlaceInfoViewController

- (instancetype)initWithPlace:(Place *)place
{
    if (self = [super init]) {
        self.place = place;
    }
    return self;
}

- (void)viewDidLoad
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self addCommonBackButton];
    
    self.navigationItem.title = @"场馆资料";
    
    CGRect rect = CGRectMake(0, 0, self.view.width, self.view.height);
    self.infoTableView = [[UITableView alloc] initWithFrame:rect];
    self.infoTableView.dataSource = self;
    self.infoTableView.delegate = self;
    [self.view addSubview:self.infoTableView];
    
    self.infoTableView.tableFooterView = [[UIView alloc] init];
    
    [self getActivity];
    [self getPhotoNumber];
    
    @weakify(self);
    [self.infoTableView nd_addPullToLoadMoreWithActionHandler:^(id sender) {
        @strongify(self);
        [self getActivity];
    }];
}

#pragma mark -UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 4;
    }
    
    return self.activityArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return [PlaceInfoTopCell cellHeight];
        }else if (indexPath.row == 1) {
            return [PlaceInfoAddressPhoneCell calulateCellHeightWithText:self.place.address];
        }else if (indexPath.row == 2) {
            return [PlaceInfoAddressPhoneCell calulateCellHeightWithText:self.place.telephone];
        }else {
            return [PlaceInfoBottomCell calulateCellHeightWithText:self.place.introduction];
        }
    } else if (indexPath.section == 1) {
        GroupActivity *activity = [self.activityArray objectAtIndex:indexPath.row];
        
        return [GroupInfoActivityCell calulateCellHeightWithText:activity.content];
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            PlaceInfoTopCell *topCell = [tableView dequeueReusableCellWithIdentifier:@"TopCell"];
            if (!topCell) {
                topCell = [[PlaceInfoTopCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TopCell"];
            }
            topCell.selectionStyle = UITableViewCellSelectionStyleNone;
            topCell.totalPhotoNumber = self.totalPhotoNumber;
            topCell.delegate = self;
            [topCell drawCellWithPlace:self.place];
            
            return topCell;
        }else if (indexPath.row == 1 || indexPath.row == 2) {
            PlaceInfoAddressPhoneCell *centerCell = [tableView dequeueReusableCellWithIdentifier:@"CeterCell"];
            if (!centerCell) {
                centerCell = [[PlaceInfoAddressPhoneCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CenterCell"];
            }
            if (indexPath.row == 1) {
                [centerCell drawCellWithText:self.place.address];
                centerCell.iconImageView.image = [UIImage imageNamed:@"icon_ad"];
            }else {
                [centerCell drawCellWithText:self.place.telephone];
                centerCell.iconImageView.image = [UIImage imageNamed:@"icon_tel"];
            }
            return centerCell;
        }else {
            PlaceInfoBottomCell *bottomCell = [tableView dequeueReusableCellWithIdentifier:@"BottomCell"];
            if (!bottomCell) {
                bottomCell = [[PlaceInfoBottomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BottomCell"];
            }
            [bottomCell drawCellWithText:self.place.introduction];
            return bottomCell;
        }
    } else {
        GroupInfoActivityCell *activityCell = [tableView dequeueReusableCellWithIdentifier:@"ActivityCell"];
        if (!activityCell) {
            activityCell = [[GroupInfoActivityCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ActivityCell"];
            activityCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [activityCell drawCellWithActivity:[self.activityArray objectAtIndex:indexPath.row]];
        return activityCell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            PlaceMapViewController *placeMapVC = [[PlaceMapViewController alloc] init];
            CLLocationCoordinate2D center = CLLocationCoordinate2DMake(self.place.latitude, self.place.longitude);
            placeMapVC.center = center;
            [self.navigationController pushViewController:placeMapVC animated:YES];
        }else if (indexPath.row == 2){
            [self callPhone];
        }
    }
}

- (void)callPhone {
    //打电话
    NSArray *telArray = [self.place.telephone componentsSeparatedByString:@","];
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"拨打" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil];
    for (NSString *tel in telArray) {
        [actionSheet addButtonWithTitle:tel];
    }
    [actionSheet showInView:self.view];
}

#pragma mark - PlaceInfoTopCellDelegate
- (void)goToPlacePhotoAction
{
    if (self.firstPhotoArray.count) {
        PlacePhotoViewController *photoVC = [[PlacePhotoViewController alloc] init];
        photoVC.placeId = self.place.place_id;
        photoVC.currentPage = 1;
        photoVC.totalPage = self.totalPhotoPage;
        
        [photoVC parsePhotoArray:self.firstPhotoArray];
        [self.navigationController pushViewController:photoVC animated:YES];
    }
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex > 0) {
        NSArray *telArray = [self.place.telephone componentsSeparatedByString:@","];
        
        NSString *tel = [telArray objectAtIndex:buttonIndex - 1];
        UIWebView *callPhoneWebVw = [[UIWebView alloc] init];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:tel]];
        [callPhoneWebVw loadRequest:request];
        [self.view addSubview:callPhoneWebVw];
    }
}

#pragma mark - Http
- (void)getActivity
{
    @weakify(self);
    [PlaceNet getPlaceActivityWithPlaceId:self.place.place_id pageNumber:self.currentPage+1 pageSize:10 successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSArray *dictArray = [[responseObject objectForKey:@"data"] objectForKey:@"list"];
            if (dictArray.count > 0) {
                if (!self.activityArray) {
                    self.activityArray = [NSMutableArray array];
                }
                
                self.currentPage = [[[responseObject objectForKey:@"data"] objectForKey:@"pageNumber"] integerValue];
                self.totalPage = [[[responseObject objectForKey:@"data"] objectForKey:@"totalPage"] integerValue];
                
                for (NSDictionary *dict in dictArray) {
                    [self.activityArray addObject:[PlaceActivity placeActivityWithDict:dict]];
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (self.currentPage == self.totalPage) {
                        ((NDRefreshLoadMoreContentView *)(self.infoTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNoMore;
                    } else {
                        ((NDRefreshLoadMoreContentView *)(self.infoTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNormal;
                    }
                    [self.infoTableView nd_endLoadMore];
                    [self.infoTableView reloadData];
                });
                
            }
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)getPhotoNumber
{
    @weakify(self);
    [PlaceNet getPlacePhotoWithPlaceId:self.place.place_id pageNumber:1 pageSize:10 successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSArray *dictArray = [[responseObject objectForKey:@"data"] objectForKey:@"list"];
            if (dictArray.count > 0) {
                self.totalPhotoNumber = [[[responseObject objectForKey:@"data"] objectForKey:@"totalRow"] integerValue];
                self.totalPhotoPage = [[[responseObject objectForKey:@"data"] objectForKey:@"totalPage"] integerValue];
                
                self.firstPhotoArray = [NSMutableArray arrayWithArray:dictArray];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.infoTableView reloadData];
                });
            }
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

@end
